import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPCopyPictureServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            Socket server = serverSocket.accept();

            String fileName = "gitee.jpg";
            File file = new File(fileName);
            long size = file.length();

            // 获取输出流，字节类型
            OutputStream outputStream = server.getOutputStream();
            // 将字节流转为字符流
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(fileName);
            bufferedWriter.write("\r\n");
            bufferedWriter.flush();

            bufferedWriter.write(Long.toString(size));
            bufferedWriter.write("\r\n");
            bufferedWriter.flush();

            FileInputStream fileInputStream = new FileInputStream(fileName);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            byte[] bytes = new byte[8192];
            int length;
            while (((length = bufferedInputStream.read(bytes)) != -1)) {
                outputStream.write(bytes, 0, length);
            }

            bufferedInputStream.close();
            fileInputStream.close();

            InputStream inputStream = server.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String info = bufferedReader.readLine();
            System.out.println(info);

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

            bufferedWriter.close();
            outputStreamWriter.close();
            outputStream.close();

            server.close();
            serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
